/**
 * 组件名称：AhrenChoice自定义选择
 * 作者：鹰鏃
 * 时间：2016-10-13
 */
/*Array.prototype.notempty = function(){
    return this.filter(t => t!="");
}*/
;(function($,win){
    'use strict';
    // 默认声明 组件名称
    var pluginName = "AhrenChoice";

    //默认配置项
    var defaults = {
        tabType:"click",//城市切换tab事件 默认为点击
        datalist:{},
        placeholder:"请选择",//输入框提示信息
        readonly:true, //输入框是否为只读
        disabled:false ,  //禁止输入框获取焦点
        floor:3,
        theme:"blue",
        catidInput:"",
        other:true
    }

    //构造函数
    var AhrenChoice = function(element,options){
        var $timestamp = new Date().getTime();
        //当前组件名称
        this._name = pluginName;
         //缓存
        this.cache = {
            nowProvinceJson:null  //当前省份数据 (格式:JSON对象) 
        };
        this._timestamp= $timestamp.toString();
        this._createDate=new Date($timestamp).toLocalDate();
        //初始化当前对象
        this._init(element,options);
    };

    //程序方法
    AhrenChoice.prototype = {
        constructor:AhrenChoice,
        _init:function(element,options){
            var self = this;
            var $timestamp = new Date().getTime();            
            //合并输入的参数
            self.config = $.extend(defaults,options || {});
            self._timestamp= $timestamp.toString();
            self._createDate=new Date($timestamp).toLocalDate();
            //渲染主容器
            self._renderWrap(element);
            //绑定输入框点击事件 打开下拉框
            self._bindSelectInputClick();
            //绑定省份、城市、区列表点击事件
            self._bindSelectListClick();
            self._bindPostAndResetBtnClick();
        },
        //根据传入的输入框 渲染主容器和基本结构
        _renderWrap:function(element){
            //获得当前实例的输入框的HTML
            var self = this,
                _config = self.config,//相关配置
                $timestamp = self._timestamp,
                $elem = $(element),
                $elemParent = $elem.parent(),
                Datalist = _config.datalist;//数据
            //设置输入框的相关属性
            $elem.addClass("Ahren_Choice-Input");
            //判断输入框是否为只读
            if(_config.readonly == false){
                $elem.attr("readonly",false);
            }else{
                $elem.attr("readonly",true);
            }
            //提示信息
            if(_config.placeholder){
                $elem.attr("placeholder",_config.placeholder);
            }

            if(_config.disabled == true){
                $elem.prop("disabled",true);
            }else{
                $elem.prop("disabled",false);
            }
            //创建主容器
            $elem.after('<div class="Ahren_Choice l_'+_config.theme+' close">');
            //当前实例的主容器
            var $AhrenChoice = $elemParent.find(".Ahren_Choice");
            //将输入框移入主容器内
            //$elem.appendTo($AhrenChoice);
            //储存主容器和输入框到实例对象上
            self.$AhrenChoice = $AhrenChoice;
            self.$AhrenInput = $elem;

            

            //插入主要内容wrap HTML
            $AhrenChoice.append('<div class="choice_wrap"><div class="col-md-12 col-sm-12 choice_col"><div class="sousuo clearfix"><div class="select-result clearfix"><ul></ul></div></div><div class="panel-group wrap choice_cont accordion"id="accordion"role="tablist"aria-multiselectable="true"></div></div><div class="choice_foot"><button class="button button-success choice-post-btn"type="button">确定</button><button class="button button-danger choice-reset-btn"type="button">清除</button><button class="button button-danger choice-close-btn"type="button">关闭</button></div></div>');
            $AhrenChoice.append('');
             self.$AhrenMask = "";

            //如果省份数据获取成功
            if(Datalist.length > 0){
                //插入省份DOM
                self._getSelectList(Datalist);
            }
            else{
                console.log("获取数据失败");
            }
        },
        /**
         * 加载选择列表
         * @param  {[type]} data [Array]
         * @param  {[type]} type [string]
         * @return {[type]}      []
         */
        _getSelectList:function(data){
            //获得省份容器和数据
            var self = this,
                $config=self.config,
                $floor=$config.floor,
                $AhrenChoice = self.$AhrenChoice, //主容器
                listDom = null;
                
            if(data){
                //获得目标容器
                 var $targetItem = $AhrenChoice.find(".choice_cont");
                if($floor==3){
                    listDom = self._render3List(data);
                }else if($floor==2){
                    listDom = self._render2List(data);
                }else{
                    console.error("暂时只支持2，3级")
                }
                $targetItem.html(listDom);
                listDom=null;
            }
        },
        /**
         * 渲染列表span DOM
         * 传入一个数组 返回一个DOM字符串
         * @param  {[type]} listArr [array]
         * @return {[type]}         [string]
         */
        _render2List:function(listArr){
             var self = this,
             $config=self.config,
             $other=$config.other;
            //返回结果
            var resultArr = [];
            //如果传入的数组存在 且 数量大于0
            if(listArr && self.isArray(listArr) && listArr.length > 0){
                //循环所有的列表项目
                var listArr1=listArr;
                var listArr2=listArr;
                var listArr3=listArr;
                for(var i in listArr1){
                    var htmlc="";
                    if(listArr1[i].d==1){
                        htmlc += '<div class="panel"><div class="panel-heading" role="tab"  title="'+listArr1[i].a+'" id="heading'+listArr1[i].a+'">'
                                  +'<h4 class="panel-title">'
                                    +'<a role="button" data-toggle="collapse" data-parent=".accordion" href="javascript:;" aria-expanded="true" aria-controls="collapse'+listArr1[i].a+'">'+listArr1[i].b+'</a>'
                                 +'</h4>'
                                +'</div>';
                            htmlc +='<div id="collapse'+listArr1[i].a+'" class="panel-collapse collapse" role="tabpanel" aria-labelledby="heading'+listArr1[i].a+'"><div class="panel-body"><div class="updown_box"> <ul class="l_checkbox" data-map="radio_'+listArr1[i].a+'">';
                                htmlc +='<li data-map="'+listArr1[i].a+'" class="dataAll"><a href="javascript:;">全部'+listArr1[i].b+'</a></li>';
                                for(var j in listArr2){
                                     if (listArr2[j].c==listArr1[i].a){
                                        htmlc += '<li data-map="'+listArr2[j].a+'"><a href="javascript:;">'+listArr2[j].b+'</a></li>';
                                     }
                                }
                                if(!$other){
                                    htmlc += '<li class="noli"><input type="text" class="other" placeholder="其他'+listArr2[j].b+'"/><input type="button" value="添加" class="Ahren_btn"/></li>';                                           
                                }
                             htmlc += '</ul>'
                            htmlc += '</div></div></div>';
                        htmlc += '</div>';
                    }
                    if(self.isNEmpty(htmlc)){
                        resultArr.push(htmlc);
                    }else{
                    }
                }
            }
            return resultArr.join("");
        },
         _render3List:function(listArr){
             var self = this,
             $config=self.config,
             $other=$config.other;
            //返回结果
            var resultArr = [];
            //如果传入的数组存在 且 数量大于0
            if(listArr && self.isArray(listArr) && listArr.length > 0){
                //循环所有的列表项目
                var listArr1=listArr;
                var listArr2=listArr;
                var listArr3=listArr;
                for(var i in listArr1){
                    var htmlc="";
                   if(listArr1[i].c==0){
                        htmlc += '<div class="panel"><div class="panel-heading" role="tab"  title="'+listArr1[i].a+'" id="heading'+listArr1[i].a+'">'
                                  +'<h4 class="panel-title">'
                                    +'<a role="button" data-toggle="collapse" data-parent=".accordion" href="javascript:;" aria-expanded="true" aria-controls="collapse'+listArr1[i].a+'">'+listArr1[i].b+'</a>'
                                 +'</h4>'
                                +'</div>';
                        if(listArr1[i].d==1){
                            htmlc +='<div id="collapse'+listArr1[i].a+'" class="panel-collapse collapse" role="tabpanel" aria-labelledby="heading'+listArr1[i].a+'"><div class="panel-body"><div class="updown_box">';
                                    htmlc +='<ul class="l_checkbox" data-map="radio_'+listArr1[i].a+'">';
                                       htmlc += '<li data-map="'+listArr1[i].a+'" class="dataAllAll"><a href="javascript:;">全部'+listArr1[i].b+'</a></li>';
                                    htmlc += '</ul>';
                                                             
                                for(var j in listArr2){
                                	
                                    if (listArr2[j].c==listArr1[i].a&&listArr2[j].c<=512){
                                        htmlc += '<h3><span>'+listArr2[j].b+'</span></h3>';
                                        htmlc += '<ul class="l_checkbox" data-map="radio_'+listArr1[i].a+'"><li data-map="'+listArr2[j].a+'" class="dataAll"><a href="javascript:;">全部'+listArr2[j].b+'</a></li>'
                                        if(listArr[j].d==1){
                                            for(var u in listArr3){
                                                if (listArr3[u].c==listArr2[j].a){
                                                    htmlc += '<li data-map="'+listArr3[u].a+'"><a href="javascript:;">'+listArr3[u].b+'</a></li>';
                                                }
                                            }
                                        }
                                        if(!$other){
                                            htmlc += '<li class="noli"><input type="text" class="other" placeholder="其他的'+listArr2[j].b+'"/><input type="button" value="添加" class="Ahren_btn"/></li>';                                           
                                        }
                                        htmlc += '</ul>'
                                    }
                                }
                            htmlc += '</div></div></div>';
                        }
                        htmlc += '</div>'
                    }
                    if(self.isNEmpty(htmlc)){
                        resultArr.push(htmlc);
                    }else{
                    }
                }
            }
            return resultArr.join("");
        },
        _bindSelectInputClick:function(){
            var self = this,
                $AhrenInput = self.$AhrenInput;
            //绑定输入框点击事件 切换显示状态
            $AhrenInput.on("click.view",function(){
                self.toggle();
            });
        },
        /**
         * 绑定列表点击事件
         * @return {[type]} [description]
         */
        _bindSelectListClick:function(){
            var self = this,
                $AhrenChoice = self.$AhrenChoice,//主容器,
                $selectCont = $AhrenChoice.find(".choice_cont"),
                $sResult=$AhrenChoice.find(".select-result"),
                $selectUl=$selectCont.find("ul"),
                $resultUl=$sResult.find("ul");

                $selectCont.delegate(".panel .panel-heading","click",function(e){
                    self._stopBubble(e);
                    var $collapse = $(this).next(".panel-collapse");
                    var $panel = $(this).parent(".panel").siblings(".panel");
                    if($(this).hasClass('active')){
                        $(this).removeClass('active');
                        $(this).next(".panel-collapse").removeClass('in');
                    }else{
                        $panel.find(".panel-collapse").removeClass('in');
                        $panel.find(".panel-heading").removeClass('active');
                        $(this).addClass('active');
                        $(this).next(".panel-collapse").addClass('in');
                    }
                })
                $(".l_radio li:not(.noli),.l_radio").unbind('click').delegate(" li:not(.dataAll)","click",function(e) {
                    self._stopBubble(e);
                    var index=$(this).index();
                    self._bindChoice({ "pclss":"l_radio","index":index,"dom":this});
                });
                $(".l_checkbox").unbind('click').delegate("li:not(.noli)","click",function(e) {
                    self._stopBubble(e);
                    var index=$(this).index();                  
                    self._bindChoice({ "pclss":"l_checkbox","index":index,"dom":this});
                });
                $selectCont.delegate(".Ahren_btn","click",function(e){
                    self._stopBubble(e);
                    var _noli =  $(this).parent(".noli");
                    var _input = _noli.find("input.other").val();
                    if(_input!=""){
                        _noli.before('<li data-map="68719542273"><a href="javascript:;">'+_input+'</a></li>');
                        self._bindSelectListClick();
                        _noli.find("input.other").val("")
                    }else{
                        return false;
                    }
                })

                $resultUl.delegate("li", "click", function(e) {
                     self._stopBubble(e);
                    var cmap = $(this).attr("data-map");
                    var cmapArr=[];
                    if(cmap.indexOf("_")>=0){
                        cmapArr=cmap.split("_")[0]
                    }
                    $(this).remove();
                    var clonepDom=$selectUl.find("[data-map="+cmap+"]");
                    clonepDom.removeClass("selected");
                });
        },
        _bindChoice:function(str){
            var self = this,
                $AhrenChoice = self.$AhrenChoice,//主容器
                $selectOpen = $(".Ahren_Choice.open"), /*$AhrenChoice.find(".choice_wrap.open"),*/
                $selectCont = $selectOpen.find(".choice_cont"),//城市列表容器
                $sResult=$selectOpen.find(".select-result"),
                $resultUl=$sResult.find("ul");
            var pdom = $(str.dom).parent("."+str.pclss);
            var ptype=pdom.attr("data-map");
            var $jObject = $resultUl.find('li[data-cmap='+ptype+']');
            var $jObject1 =  $resultUl.find('li[data-cmap='+ptype+'][data-ckey='+str.index+']');
            if(str.pclss.indexOf("radio")>=0){
                $(str.dom).addClass("selected").siblings().removeClass("selected");
                if($jObject.length<=0){
                    var cloneDom = $(str.dom).clone();
                    $(cloneDom).attr("data-cmap",ptype);
                    $(cloneDom).attr("data-ckey",str.index);
                    $(".select-result>ul").append(cloneDom);
                }else{
                    $jObject.html('<a href="javascript:;">'+$(str.dom).text()+'</a>');
                    $jObject.attr("data-ckey",str.index);
                }
            }else{
                if($(str.dom).hasClass("dataAllAll")){
                        var selected =  $(str.dom).parents(".updown_box").find("li.selected");
                        selected.each(function(index, el) {
                            var dataMap = $(el).attr("data-map");
                            var RMap = $resultUl.find("li[data-map="+dataMap+"]");
                            RMap.remove();
                        });
                        selected.removeClass("selected");
                        $(str.dom).addClass("selected");
                        var rRMap = $resultUl.find("li[data-map="+ptype+"]");
                    if(rRMap.length>0){
                        
                    }else{
                        var cloneDom = $(str.dom).clone();
                        $(cloneDom).attr("data-cmap",ptype);
                        $(cloneDom).attr("data-ckey",str.index);
                        $resultUl.append(cloneDom);
                    }
                }else if($(str.dom).hasClass("dataAll")){
                    var selected =  $(str.dom).parent().find("li.selected");
                    
                    var dataAll = $(str.dom).parents(".updown_box").find(".dataAllAll");
                    var dataMap = dataAll.attr("data-map");
                    var dataCap = dataAll.parent().attr("data-map");
                    var RMap = $resultUl.find("li[data-map="+dataMap+"]");
                    RMap.remove();
                    dataAll.removeClass("selected");




                    selected.each(function(index, el) {
                        var dataMap = $(el).attr("data-map");
                        var RMap = $resultUl.find("li[data-map="+dataMap+"]");
                        RMap.remove();
                    });
                    $(str.dom).parent().find("li.selected").removeClass("selected");
                    $(str.dom).addClass("selected");
                    var rRMap = $resultUl.find("li[data-map="+ptype+"]");
                    if(rRMap.length>0){
                        
                    }else{
                        var cloneDom = $(str.dom).clone();
                        $(cloneDom).attr("data-cmap",ptype);
                        $(cloneDom).attr("data-ckey",str.index);
                        $resultUl.append(cloneDom);
                    }
                }else{
                    var dataAll1 = $(str.dom).parents(".updown_box").find(".dataAllAll");
                    var dataMap1 = dataAll1.attr("data-map");
                    var dataCap1 = dataAll1.parent().attr("data-map");
                    var RRMap = $resultUl.find("li[data-map="+dataMap1+"]");
                    RRMap.remove();
                    dataAll1.removeClass("selected");


                    var dataAll = $(str.dom).parent().find(".dataAll");
                    var dataMap = dataAll.attr("data-map");
                    var dataCap = dataAll.parent().attr("data-map");
                    var RMap = $resultUl.find("li[data-map="+dataMap+"]");
                    RMap.remove();
                    $(str.dom).parent().find(".dataAll").removeClass("selected");
                    $(str.dom).addClass("selected");
                     var daMap =  $(str.dom).attr("data-map");
                    var rRMap = $resultUl.find("li[data-map="+daMap+"]");


                    if(rRMap.length>0){
                        $(str.dom).removeClass("selected");
                        $resultUl.find("li[data-map="+daMap+"]").remove();
                    }else{
                        var cloneDom = $(str.dom).clone();
                        $(cloneDom).attr("data-cmap",ptype);
                        $(cloneDom).attr("data-ckey",str.index);
                        $resultUl.append(cloneDom);
                    }
                }
            }
        },
       _stopBubble:function(event){
            var e=event || window.event;
            if (e && e.stopPropagation){
                e.stopPropagation();    
            }else{
                e.cancelBubble=true;
            }
        },
        _stopDefault:function(e) {
             // 阻止默认浏览器动作(W3C)
             if ( e && e.preventDefault ) {
                 e.preventDefault();
             } else {
                // IE中阻止函数器默认动作的方式
                window.event.returnValue = false;
            }
            return false;
        },
        isArray:function(obj){
            return Object.prototype.toString.apply(obj) === '[object Array]';
        },
        isEmpty: function(str) {
            if ((str == null || typeof(str) == "undefined") || (typeof(str) == "string" && str == "" && str != "undefined")) {
                return true;
            } else {
                return false;
            }
        },
        isNEmpty: function(str) {
            if ((str == null || typeof(str) == "undefined") || (typeof(str) == "string" && str == "" && str != "undefined")) {
                return false;
            } else {
                return true;
            }
        },
        // 绑定确定按钮和清除按钮点击事件
        _bindPostAndResetBtnClick:function(){
            //获得确定按钮
            var self = this,
                _config = self.config,//配置
                _catInput = _config.catidInput,
                $AhrenChoice = self.$AhrenChoice,//主容器
                $postBtn = $AhrenChoice.find(".choice-post-btn"),//确定按钮
                $resetBtn = $AhrenChoice.find(".choice-reset-btn"),
                $closeBtn = $AhrenChoice.find(".choice-close-btn"),//清除按钮按钮
                $selectOpen = $AhrenChoice.find(".choice_wrap.open"),
                $selectCont = $selectOpen.find(".choice_cont");//城市列表容器
                
            //确定按钮点击事件
            $postBtn.on("click.choice-post",function(){
                var choiceWrap =  $(".Ahren_Choice.open").find(".choice_wrap");
                var choiceResult=choiceWrap.find(".select-result ul li");
                var $AhrenInput = self.$AhrenInput;
                var resetB="";
                var resetCat="";
                if(choiceResult.length>0){
                    for(var i =0;i< choiceResult.length;i++){
                       resetCat+=( choiceResult[i].attributes["data-map"].value )+",";
                       resetB+=( choiceResult[i].innerText)+",";
                    }
                    resetB=resetB.substr(0,(resetB.length-1));
                    resetCat=resetCat.substr(0,(resetCat.length-1));
                }               
                var arr=["512","66048","131584","262656","524800","1049088",]; 
                for(var i =0;i<arr.length;i++){
                	if(resetCat.indexOf(arr[i])>-1){
                		typedpn();
                		resetB+="高新技术"
                		break;
                	}else{
                		typedpb();
                	}             	
                }
                $("prdMineral").val(resetB);
                $AhrenInput.val(resetB)
                $(_catInput).val(resetB);
                self.toggle();
            });
            //关闭按钮
            $closeBtn.on("click.choice-close",function(){
            	self.hide();
            });
            //清除按钮点击事件
            $resetBtn.on("click.choice-resets",function(){
                var choiceWrap = $(".Ahren_Choice.open").find(".choice_wrap");
                var $sResult=choiceWrap.find(".select-result");
                var choiceResult=choiceWrap.find("ul li");
                var _catVal=$(_catInput).val();
                choiceResult.removeClass("selected");
                $sResult.html("<ul></ul>");
                if(_catVal!=""){
                    $(_catInput).val("");
                }
            });
        },
        //切换状态
        toggle: function() {
          //判断当前是否打开
          if(this.$AhrenInput.data('AhrenChoice') === 'show') {
            this.hide();
            $("html").removeClass('open');
          }
          else {
            this.show();
            $("html").addClass('open');
          }
        },
        //显示选择控件
        show:function(){
            this.$AhrenInput.data('AhrenChoice', 'show');
            this.$AhrenInput.next().addClass("open").removeClass('close');
        },
        //隐藏选择控件
        hide:function(){
            this.$AhrenInput.data('AhrenChoice', 'hide');
            this.$AhrenInput.next().addClass("close").removeClass('open');
        },
    };
    Date.prototype.Format = function (fmt) { //author: meizz 
        var o = {
            "M+": this.getMonth() + 1, 
            "d+": this.getDate(), 
            "H+": this.getHours(),  
            "m+": this.getMinutes(),  
            "s+": this.getSeconds(), 
            "q+": Math.floor((this.getMonth() + 3) / 3), 
            "S": this.getMilliseconds()  
        };
        var year = this.getFullYear();
        var yearstr = year + '';
        yearstr = yearstr.length >= 4 ? yearstr : '0000'.substr(0, 4 - yearstr.length) + yearstr;
        
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (yearstr + "").substr(4 - RegExp.$1.length));
        for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    };
    Date.prototype.toLocalDate = function() {
        var fmt="yyyy/MM/dd HH:mm";
        return this.Format(fmt);
    }
    //将组件设置到jQuery中
    $.fn[pluginName] = function(options){
        return this.each(function(){
            //判断是否已经存在当前实例 如果存在则进行切换状态 否则创建一个新的实例
            if ($.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName).toggle();
            }
            else {
                $.data(this, "plugin_" + pluginName, new AhrenChoice(this,options));
            }
        });
    }
    //页面其他位置点击隐藏组件
    $(document).on("click",".Ahren_Choice",function(e){
        var $targetObj = $(e.target),//当前点击对象
            $AhrenParent = $targetObj.parents(".Ahren_Choice");
        if($targetObj.hasClass("Ahren_Choice")){
        	//$.data(this, "plugin_" + pluginName).hide();
        }else if($AhrenParent.hasClass("Ahren_Choice")){
        	return false;
        }
    });
})(jQuery||Zepto,window);